package com.terra.ns.imp.common.web.idempotent

import cn.hutool.crypto.SecureUtil
import cn.hutool.json.JSONUtil
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.reflect.MethodSignature
import org.springframework.web.multipart.MultipartFile

/**
@author qins
@date 2022/4/14
@desc 默认幂等操作的key解析器 ： 将方法名+参数使用md5加密得到key
 */
class DefaultIdempotentKeyResolver: IdempotentKeyResolver {
    /**
     *@param joinPoint 切面
     * @return 得到解析后的唯一key
     */
    override fun resolver(joinPoint: JoinPoint): String {
        val methodName = joinPoint.signature.toString()
        val param = doLogRequestParam(joinPoint)
        val paramStr = if(param.isEmpty()) "" else JSONUtil.toJsonStr(param)
//        val argsStr = StrUtil.join(",", *joinPoint.args)
        return SecureUtil.md5(methodName + paramStr)
    }

    private fun doLogRequestParam(point: JoinPoint): Map<String, String?> {
        val paramNameList = (point.signature as MethodSignature).parameterNames
        val args = point.args
        val param = HashMap<String, String?>()
        args.forEachIndexed{ index, item ->
            val paramVal = if (item is MultipartFile) {
                item.originalFilename
            } else {
                JSONUtil.toJsonStr(item)
            }
            param[paramNameList[index]] = paramVal
        }
        return param
    }
}